package com.hliushi.bookmanager.controller.admin;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hliushi.bookmanager.mapper.BookMapper;
import com.hliushi.bookmanager.pojo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/admin/book")
public class AdminBookController {

    @Autowired
    private BookMapper bookMapper;

    @RequestMapping("/getAll")
    public String getAll(Model model) {
//        List<Book> blogs = bookMapper.getAllBook();
        List<Book> blogs = bookMapper.selectList(null);
        model.addAttribute("blogs", blogs);
        return "admin/blogs";
    }

    @RequestMapping("/info/{id}")
    public String info(Model model, @PathVariable("id") String id) {
//        Book book = bookMapper.getBookById(id);
        Book blog = bookMapper.selectById(id);
        model.addAttribute("blog", blog);

        return "admin/blog_info";
    }

    @RequestMapping("/toEditPage/{id}")
    public String toEditPage(Model model, @PathVariable("id") String id) {
//        Book book = bookMapper.getBookById(id);
        Book blog = bookMapper.selectById(id);
        model.addAttribute("blog", blog);
        return "admin/blog_edit";
    }

    @RequestMapping("/update")
    public String update(Book book) {
//        bookMapper.updateBook(book);
        bookMapper.update(book, Wrappers.<Book>lambdaQuery().eq(Book::getBookId,book.getBookId()));
        return "redirect:/admin/book/getAll";
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") long id) {
//        bookMapper.deleteBook(id);
        bookMapper.deleteById(id);
        return "redirect:/admin/book/getAll";
    }

    @RequestMapping("/toAddPage")
    public String toAddPage() {
        return "admin/blog_add";
    }

    @RequestMapping("/add")
    public String add(Book book) {
//        bookMapper.addBook(book);
        bookMapper.insert(book);
        return "redirect:/admin/book/getAll";
    }

    @RequestMapping("/search")
    public String search(String keyword, Model model) {
//        List<Book> books = bookMapper.searchBook(keyword);
        List<Book> books = bookMapper.selectList(Wrappers.<Book>lambdaQuery()
                .like(Book::getName, keyword)
                .or()
                .like(Book::getSimplecontext, keyword)
                .or()
                .like(Book::getAuthor, keyword));
        model.addAttribute("blogs", books);
        return "admin/bolg_search_result";
    }
}
